import { defineConfig } from "vite";
import AutoImport from 'unplugin-auto-import/vite';
import uni from "@dcloudio/vite-plugin-uni";
import ViteAutoComponents from 'unplugin-vue-components/vite'
import path from "path"
import fs from 'fs'

export default defineConfig({
  plugins: [
    uni(),
    AutoImport({
      imports: [
        'vue',
        'uni-app'
      ],
      dts: 'src/auto-import.d.ts',
    }),
    ViteAutoComponents({
      dirs: ['src/components'],
      extensions: ['vue'],
      dts: 'src/types/auto-components.d.ts',
    }),
  ],
  build: {
    // target: 'h5',
    // outDir: 'dist/h5',
  },
  base: './',
  resolve: {
    alias: {
      // 这里就是需要配置resolve里的别名
      "@": path.join(__dirname, "./src") // path记得引入
    }
  },
  server: {
    // port: 8080,
    port: 8888,
    // open: true,
    proxy: {
      '/sys/': {
        target: 'http://csbestclient.atbjy.com/h5/', // 开发环境
        changeOrigin: true
      },
      '/api/': {
        target: 'http://csbestclient.atbjy.com/h5/', // 开发环境
        changeOrigin: true
      },
      '/drone/': {
        target: 'http://localhost:8080', // 后端API代理
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/drone/, '/drone')
      }
    },
    cors: true,
    // 自定义中间件：将以 /login 开头的路径重写到 index.html（解决 H5 直接访问 /login 404）
    configureServer(server) {
      const indexHtmlPath = path.resolve(__dirname, 'index.html')
      let cachedIndexHtml: string | null = null
      server.middlewares.use((req, res, next) => {
        const url = req.url || ''
        if (/^\/login(\/?|$)/.test(url)) {
          try {
            if (!cachedIndexHtml) {
              cachedIndexHtml = fs.readFileSync(indexHtmlPath, 'utf-8')
            }
            res.statusCode = 200
            res.setHeader('Content-Type', 'text/html; charset=utf-8')
            res.end(cachedIndexHtml)
            return
          } catch (e) {
            // 读取失败则继续交给后续中间件处理
          }
        }
        next()
      })
    }
  },
});
